package online.longzipeng.mywebdemo.mq.consumer;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @Author: lzp
 * @description: 订阅发布模式，[direct]直连
 * 与广播模式仅交换机不一样，交换机根据routeKey决定把消息发送给某个消费队列
 * @Date: 2024/1/14
 */
@Component
public class DirectConsumer {

	//队列名称常量
	public static final String QUEUE_NAME1 = "direct_queue1";
	public static final String QUEUE_NAME2 = "direct_queue2";
	//交换机名称常量
	public static final String EXCHANGE_NAME = "direct_exchange";

	/** ======================= 订阅模式， 直连，一个扇形交换机，两个消费队列 =========================*/

	/**
	 * 声明队列 Queue
	 */
	@Bean
	public Queue directQueue1() {
		return new Queue(QUEUE_NAME1, true, false, false, null);
	}

	/**
	 * 声明队列 Queue
	 */
	@Bean
	public Queue directQueue2() {
		return new Queue(QUEUE_NAME2, true, false, false, null);
	}


	/**
	 * 声明交换机
	 */
	@Bean
	DirectExchange directExchange() {
		return new DirectExchange(EXCHANGE_NAME,true,false,null);
	}

	/**
	 * 交换机队列绑定
	 */
	@Bean
	Binding bindingDirectExchange1(@Autowired Queue directQueue1,@Autowired DirectExchange directExchange) {
		return BindingBuilder.bind(directQueue1).to(directExchange).with("q1");
	}

	@Bean
	Binding bindingDirectExchange2(@Autowired Queue directQueue2,@Autowired DirectExchange directExchange) {
		return BindingBuilder.bind(directQueue2).to(directExchange).with("q2");
	}



	/** 订阅模式， 直连，两个消费者 */
	@RabbitListener(queues = "direct_queue1")
	public void receive1(String msgData, Message message, Channel channel) throws IOException {
		channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
		System.out.println("direct_queue1消费者收到消息  : " +msgData);
	}

	@RabbitListener(queues = "direct_queue2")
	public void receive2(String msgData, Message message, Channel channel) throws IOException {
		channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
		System.out.println("direct_queue2消费者收到消息  : " +msgData);
	}

}
